﻿using Helpers;
using QFramework;
using UnityEngine;

namespace Gp.Scripts.Core {
    public class HumanoidModel : UnitModel {
        [SerializeField] public CombatantWeaponPivot weaponPivot;

        private SkillAnimationSet _curSkillAnimation;

        private AnimatorOverrideController OverrideController { get; set; }


        protected override void OnInit() {
            OverrideController = new AnimatorOverrideController(Animator.runtimeAnimatorController);
            Animator.runtimeAnimatorController = OverrideController;
            Animator.applyRootMotion = false;
            transform.LocalPositionIdentity();

            SetLayers();

            if (weaponPivot == null) {
                weaponPivot = GetComponent<CombatantWeaponPivot>();
                if (weaponPivot) weaponPivot.Model = this;
            }


            UnitReference.RegisterEvent<Event_Unit.BattleEnd>(ToNormalMode);
            UnitReference.RegisterEvent<Event_Unit.BattleStart>(ToBattleMode);
            UnitReference.RegisterEvent<Event_Unit.Highlight>(OnUnitHighlight);
            UnitReference.RegisterEvent<Event_Unit.DeHighlight>(OnUnitDeHighlight);
        }

        private void OnUnitDeHighlight(Event_Unit.DeHighlight obj) {
            UnitReference.DisableHighlightEffect();
        }

        private void OnUnitHighlight(Event_Unit.Highlight obj) {
            UnitReference.TriggerHighlightEffect();
        }

        private void ToBattleMode(Event_Unit.BattleStart args) {
            // 设置动画机为战斗模式
            Animator.SetBool(UnitAnimatorParameter.IsBattleModeBool, true);
            // 触发切换武器
            ActionKit
                .Delay(Random.Range(0, .25f),
                    () => GestureTrigger(new ChangeWeaponGestureTrigger(UnitReference.ComEquip.CurWeapon)))
                .Start(this);
        }

        private void ToNormalMode(Event_Unit.BattleEnd args) {
            Animator.SetBool(UnitAnimatorParameter.IsBattleModeBool, false);

            // // 销毁武器
            // if (weaponPivot) {
            //     Destroy(weaponPivot.CurWeapon.gameObject);
            // }
        }


        protected override void OnAnimationEvent(string eventName) {
            base.OnAnimationEvent(eventName);
            if (weaponPivot is { } pivot)
                pivot.OnUnitModelAnimationEvent(eventName);
        }

        private void SetLayers() {
            gameObject.SetAllLayer(LayerEnum.BattleCharacter.ToLayerInt());
        }
    }
}